import traceback
from datetime import datetime
from typing import List

from apps.db import db
from apps.logger_config import logger
from apps.model import BankSideInfo
from apps.seleuinms.requests import YzyhRequest, Shangdaitong, NormalLoan
from apps.service import delete_all_data
from apps.utils import curtime


def get_cookie_item(value):
    return {
        'domain': '22.230.57.12',
        'httpOnly': True,
        'name': 'tgc-credit-webpage',
        'path': '/',
        'sameSite': 'Lax',
        'secure': False,
        'value': value
    }


index_url = "http://22.230.57.12:8080/index/#index"
task_url = "http://22.230.57.12:8080/index/#/backlog/list?_=V161043656593910"


def init_bank_info(businessKeys: List[dict], data: List, cookies):
    """
    初始化所有相关数据
    包含借款人信息，合同信息，房屋信息
    """
    businessMap = {}
    for i in businessKeys:
        businessMap[i.get('business_key')] = i.get('state')

    keys = list(businessMap.keys())
    for item in data:
        b_key = item.get('businessKey')

        if businessMap.get(b_key) is not None and businessMap.get(b_key) != 'waitUpload':
            continue

        if b_key in keys:
            """存在就删除"""
            from apps.app import app
            with app.app_context():
                banks: List[BankSideInfo] = BankSideInfo.filter_by(business_key=b_key).all()
                for bank in banks:
                    delete_all_data(bank.id)
                db.session.commit()

        """
        baseWorkFlowName:
        个人一手房贷款, 个人一手商业用房贷款
        个人二手房贷款, 个人二手商业用房贷款
        （经营贷）极速贷，商通贷，农商贷，个人消费综合贷款
        """
        flow_name = item.get('baseWorkFlowName')
        if flow_name in ['个人一手房贷款', '个人一手商业用房贷款']:
            NormalLoan(item, cookies).get_data()
            continue
        if flow_name in ['个人二手商业用房贷款', '个人二手房贷款']:
            NormalLoan(item, cookies).get_data(state='waitApprove')
            continue
        Shangdaitong(item, cookies).get_data()


class YzyhThread:
    __job_name__ = '房管局填报系统'

    def __init__(self, cookies=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.start_url = index_url
        if YzyhRequest.cookie_dict:
            self.cookies = [get_cookie_item(YzyhRequest.cookie_dict.get('tgc-credit-webpage'))]
        else:
            self.cookies = []
        if cookies is not None:
            self.cookies = cookies
        self.request = YzyhRequest()

    def login(self):
        if self.cookies is None or len(self.cookies) == 0:
            cookie = self.request.login()
            self.cookies = []
            self.cookies.append(get_cookie_item(cookie.get('tgc-credit-webpage')))

    def get_task_list(self, name=None, cert_no=None):
        # 获取代办中的数据,填入history中
        params = {}
        if name is not None:
            params['customName'] = name
        if cert_no is not None:
            params['cardID'] = cert_no
        res = self.request.get_task_list(params=params)
        total_size = res.get('data').get('grid').get('total')
        if total_size == 0:
            raise Exception(500, '未找到贷款合同数据')
        if total_size > 0:
            data = res.get('data').get('grid').get('list')
            businessKeys = [d.get('businessKey') for d in data]
            sql = """
                select business_key, state from tb_bank_side_info where business_key in ({keys})
            """.format(keys=",".join(["'{v}'".format(v=v) for v in businessKeys]))
            from apps.app import app
            with app.app_context():
                infos = [dict(d) for d in db.session.execute(sql).fetchall()]
            init_bank_info(infos, data, self.request.cookie_dict)

    def executor(self, name: str = None, cert_no: str = None):
        try:
            logger.info('*' * 36)
            logger.info('程序：%s, 开始时间：%s', self.__job_name__, datetime.now().isoformat())
            self.login()

            self.get_task_list(name, cert_no)
            logger.info('程序：%s, 结束时间：%s', self.__job_name__, datetime.now().isoformat())
            # 等待10分钟时间
        except Exception as e:
            if e.args[0] == '403':
                logger.info('会话失效， 重新登录， time: %s', curtime())
                self.cookies.clear()
                YzyhRequest.cookie_dict.clear()
                self.executor(name, cert_no)
                return
            logger.error("执行任务失败: %s", traceback.format_exc())
            raise e
